<script setup>
import { ref, onMounted } from 'vue';
import { ElButton, ElInput, ElRadioGroup, ElRadio } from 'element-plus';
import { DocumentCopy } from '@element-plus/icons-vue';
import EasyQRCode from 'easyqrcodejs';

import { useUseStore } from "@/stores/user";
import TopButton from "@/components/Pengyq/TopButton.vue";
import { useI18n } from "vue-i18n";
const { t } = useI18n();
import { ToastFun } from "@/hook/toast";
import { computedBuyeCNYApi } from "@/server/web3.js"

// 数据初始化
const rechargeAddress = ref('');  // 充值地址
const rechargeAmount = ref(null);  // 动态绑定充值金额
const ETHAmount = ref('');
const OneETHAmount = ref('');
const qrCodeStatus = ref(false);  // 存储生成的二维码URL
const selectedCurrency = ref('eCNY');  // 充值货币类型，默认为 eCNY

const token = {
  address: '0x20Aa6C3F101B6246326b7DDe2a0dbC7EbB621308',
  chainId: 11155111
}

// 生成二维码
const generateQRCode = async () => {
    // 创建新的二维码
    let qrContent = '';
    if (selectedCurrency.value === 'ETH') {
      qrContent = `ethereum:${token.address}@${token.chainId}/buyTokensWithETH?address=<receivingAddress>&value=${rechargeAmount.value}e18`;
    } else if (selectedCurrency.value === 'eCNY') {
      qrContent = `ethereum:${token.address}@${token.chainId}/transfer?address=${rechargeAddress.value}&uint256=${rechargeAmount.value}e6`;
    }

    const options = {
      text: qrContent,
      width: 200,
      height: 200,
      colorDark: "#000000",
      colorLight: "#ffffff",
      correctLevel: EasyQRCode.CorrectLevel.H
    };

    // 创建新的 EasyQRCode 实例并生成二维码
    const qrcode = new EasyQRCode('qr-code-container', options);
    qrcode.makeCode(qrContent); // 生成二维码
    qrCodeStatus.value = true;
};

const closeQRCode = () => {
  const container = document.getElementById('qr-code-container');
  if (container) {
    // 清空容器的内容
    container.innerHTML = '';
  }
};

// 复制充值地址
const copyAddress = () => {
  navigator.clipboard.writeText(rechargeAddress.value)
    .then(() => {
      ToastFun("show", { msg: t("exchangeTopUp.copySuccess") });
    })
    .catch((err) => {
      ToastFun("show", { msg: t("exchangeTopUp.copyFailed") });
    });
};

// 打开充值区域，生成充值地址二维码
const openRecharge = async () => {
  qrCodeStatus.value = false;
    // 获取二维码容器
    closeQRCode();
  if (rechargeAmount.value < 0.008 && selectedCurrency.value === 'ETH') {
    ToastFun("show", { msg: t("exchangeTopUp.enterValidAmount") });
    return;
  } else if (rechargeAmount.value <= 0 && selectedCurrency.value === 'eCNY') {
    ToastFun("show", { msg: t("exchangeTopUp.enterValidAmount") });
    return;
  }
  if (selectedCurrency.value === 'ETH') {
    // 计算
    ETHAmount.value = await computedBuyeCNYApi(rechargeAmount.value);
  }
  generateQRCode();  // 生成二维码
};


onMounted(async () => {
  OneETHAmount.value = await computedBuyeCNYApi(1);
  rechargeAddress.value = useUseStore().userInfo.walletAddress;
  console.log(useUseStore().userInfo.walletAddress);
})
</script>

<template>
  <div class="page-content">
    <!-- 顶部按钮 -->
    <TopButton :title="$t('exchangeTopUp.topUp')" class="top-button" />

    <!-- 充值卡片 -->
    <div class="recharge-card">
      <!-- 充值类型选择 -->
      <div class="currency-selector">
        <p class="label">{{ t('exchangeTopUp.selectRechargeMethod') }}：</p>
        <el-radio-group v-model="selectedCurrency" @change="qrCodeStatus = false,closeQRCode()" class="radio-group">
          <el-radio value="eCNY" class="radio-option">
            <img src="https://cryptologos.cc/logos/tether-usdt-logo.png" alt="eCNY" class="currency-icon" />
            eCNY
          </el-radio>
          <el-radio value="ETH" class="radio-option">
            <img src="https://cryptologos.cc/logos/ethereum-eth-logo.png" alt="ETH" class="currency-icon" />
            ETH
          </el-radio>
        </el-radio-group>
      </div>
      <p class="currency-type" v-if="selectedCurrency === 'eCNY'">{{ $t('exchangeTopUp.use_eCNY_to_top_up_points_ratio')
        }} 1:1</p>
      <p class="currency-type" v-else="selectedCurrency === 'ETH'">{{ $t('exchangeTopUp.use_ETH_to_top_up_eCNY_ratio')
        }} 1:{{ OneETHAmount }}</p>
      <!-- 充值地址 -->
      <div v-if="rechargeAddress" class="address-container">
        <p class="label">{{ t('exchangeTopUp.rechargeAddress') }}</p>
        <div class="address-content">
          <el-input v-model="rechargeAddress" readonly class="address-input" />
          <!-- 将复制按钮放在地址后面 -->
          <el-button @click="copyAddress" class="copy-btn">
            <el-icon>
              <DocumentCopy class="copy-icon" />
            </el-icon>
          </el-button>
        </div>
      </div>

      <!-- 输入充值金额 -->
      <div class="amount-container">
        <p class="label">{{ t('exchangeTopUp.enterRechargeAmount') }}</p>
        <el-input v-model="rechargeAmount" type="number" class="input-amount"
          :placeholder="t('exchangeTopUp.enterAmount')" />
      </div>

      <!-- 显示二维码 -->
      <div id="qr-code-container"> </div>
      <div v-if="qrCodeStatus" class="qr-code-container">
        <p class="currency-type">{{ t('exchangeTopUp.rechargeType') }}{{ selectedCurrency }}</p>
        <p class="currency-type" v-if="selectedCurrency === 'eCNY'">{{ $t('exchangeTopUp.total_amount_you_can_get')
          }}:
          {{ rechargeAmount }} {{ $t('exchangeTopUp.points') }}</p>
        <p class="currency-type" v-else>{{ $t('exchangeTopUp.estimated_eCNY_to_receive') }}: {{ ETHAmount }} eCNY</p>
      </div>
      <!-- 充值按钮 -->
      <el-button @click="openRecharge" type="primary" size="large" class="recharge-button">{{ t('exchangeTopUp.confirm')
        }}</el-button>

      <!-- 充值说明 -->
      <div class="recharge-notice">
        <p>{{ t('exchangeTopUp.rechargeNotice') }}</p>
        <ul>
          <li>{{ t('exchangeTopUp.minRechargeAmount') }}</li>
          <li>{{ t('exchangeTopUp.noNonECNYAssets') }}</li>
          <li>{{ t('exchangeTopUp.networkConfirmationRequired') }}</li>
          <li>{{ t('exchangeTopUp.securityReminder') }}</li>
        </ul>
      </div>
    </div>
  </div>
</template>

<style scoped>
/* 适应手机屏幕 */
.page-content {
  padding: 20px;
  background-color: #f8f8f8;
  min-height: 100vh;
  color: #333;
  display: flex;
  flex-direction: column;
  align-items: center;
}

/* 顶部按钮样式 */
.top-button {
  background-color: #333;
  /* 黑色背景 */
  color: white;
  /* 白色文字 */
  padding: 10px 20px;
  /* 给按钮一些内边距 */
  border-radius: 8px;
  /* 按钮圆角 */
  margin-bottom: 20px;
  width: 100%;
}

/* 充值卡片样式 */
.recharge-card {
  background-color: #ffffff;
  padding: 20px;
  border-radius: 10px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  width: 100%;
  margin-top: 30px;
  text-align: center;
}

.recharge-card:hover {
  transform: scale(1.02);
}

/* 充值类型选择 */
.currency-selector {
  margin-top: 50px;
  margin-bottom: 30px;
}

.radio-group {
  display: flex;
  justify-content: center;
  margin-top: 20px;
  gap: 50px;
}

.radio-option {
  display: flex;
  align-items: center;
  font-size: 16px;
}

.currency-icon {
  width: 40px;
  height: 40px;
  margin-left: 10px;
  margin-right: 10px;
}

.el-radio-button.is-checked .currency-icon {
  border: 2px solid #007BFF;
  padding: 2px;
  border-radius: 50%;
}

/* 充值按钮样式 */
.recharge-button {
  width: 100%;
  font-size: 16px;
  padding: 12px;
  margin-top: 20px;
  border-radius: 8px;
  background: linear-gradient(135deg, #000000, #000000);
  color: #fff;
}

.recharge-button:hover {
  background-color: #3382c8;
}

/* 输入充值金额样式 */
.amount-container {
  margin-top: 20px;
  margin-bottom: 20px;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.amount-container .label {
  font-size: 16px;
  margin-bottom: 10px;
  color: #333;
}

.input-amount {
  width: 100%;
  font-size: 16px;
  padding: 12px;
  background-color: #f0f0f0;
  color: #333;
  border: 1px solid #ccc;
  border-radius: 5px;
}

/* 充值地址显示容器 */
.address-container {
  margin-top: 20px;
}

.address-container .label {
  font-size: 16px;
  margin-bottom: 10px;
  color: #333;
}

.address-content {
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: space-between;
  margin-top: 10px;
}

.address-input {
  font-size: 16px;
  padding: 12px;
  background-color: #f0f0f0;
  color: #333;
  border: 1px solid #ccc;
  border-radius: 5px;
  margin-right: 10px;
  flex: 1;
}

.copy-btn {
  width: 40px;
  height: 40px;
  /* display: inline-flex; */
  align-items: center;
  justify-content: center;
  padding: 5px 10px;
  background-color: #e2dada;
  color: rgb(0, 0, 0);
}

.copy-icon {
  font-size: 20px;
}

.qr-code-container {
  margin-top: 20px;
  text-align: center;
}

.currency-type {
  font-size: 14px;
  color: #333;
}

/* 充值说明 */
.recharge-notice {
  margin-top: 30px;
  font-size: 14px;
  color: #666;
  background-color: #f9f9f9;
  /* 背景色 */
  padding: 20px;
  border-radius: 8px;
  /* 圆角 */
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  /* 阴影 */
  border-left: 5px solid transparent;
  /* 为渐变效果做准备 */
  border-image: linear-gradient(to bottom, #c6f1ec, #10c2aa);
  /* 左侧渐变边框 */
  border-image-slice: 1;
  /* 使渐变应用到整个边框 */
}

.recharge-notice p {
  font-size: 16px;
  font-weight: bold;
  color: #333;
  margin-bottom: 15px;
  text-transform: uppercase;
  /* 强调标题 */
  letter-spacing: 1px;
  /* 字母间距 */
}

.recharge-notice ul {
  padding-left: 20px;
  text-align: left;
  list-style: none;
  /* 去掉默认项目符号 */
}

.recharge-notice li {
  margin-bottom: 10px;
  line-height: 1.5;
  color: #333;
  position: relative;
  /* 为伪元素提供位置 */
  padding-left: 25px;
  /* 给每个项添加左侧内边距 */
}

.recharge-notice li:before {
  content: '•';
  /* 使用圆点符号 */
  position: absolute;
  left: 0;
  top: 0;
  color: #000000;
  /* 圆点颜色 */
  font-size: 18px;
  /* 圆点大小 */
}
</style>
